package network.server.handler.StudentHandler;

import common.model.Entity.Student;
import module.auth.StudentService;
import module.auth.impl.StudentServiceImpl;
import network.protocol.Request;
import network.protocol.Response;
import network.server.RequestHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 学生服务处理器，用于处理客户端发来的学生信息相关请求。
 * <p>
 * 支持的操作包括：
 * <ul>
 *     <li>SearchStuStatusA - 按ID查询学生学籍信息</li>
 *     <li>SearchStuStatusB - 按用户名查询学生学籍信息</li>
 *     <li>SetStuStatusA - 设置学生学籍信息（参数方式）</li>
 *     <li>SetStuStatusB - 设置学生学籍信息（对象方式）</li>
 *     <li>UpdateStuStatusA - 更新学生学籍信息（参数方式）</li>
 *     <li>UpdateStuStatusB - 更新学生学籍信息（对象方式）</li>
 *     <li>SearchAllStuStatus - 查询所有学生学籍信息</li>
 * </ul>
 * <p>
 * 该处理器会根据请求中的 "action" 字段判断具体操作，并调用 {@link StudentService} 完成业务逻辑。
 */
public class StudentServiceHandler implements RequestHandler {
    private final StudentService studentService;
    private static final Logger logger = LoggerFactory.getLogger(StudentServiceHandler.class);

    /**
     * 默认构造函数，使用 {@link StudentServiceImpl} 单例
     */
    public StudentServiceHandler() {
        studentService = StudentServiceImpl.getInstance();
    }

    /**
     * 带参数构造函数，可自定义 StudentService 实例
     *
     * @param studentService 学生服务实例
     */
    public StudentServiceHandler(StudentService studentService) {
        this.studentService = studentService;
    }

    /**
     * 根据请求 action 分发到具体处理方法
     *
     * @param req 客户端请求
     * @return 操作结果 {@link Response}
     */
    @Override
    public Response<?> handle(Request req) {
        String action = req.getAction();
        logger.info("到达StudentServiceHandler");
        String[] splitAction = action.split("\\.");

        return switch (splitAction[1]) {
            case "SearchStuStatusA" -> handleSearchById(req);
            case "SearchStuStatusB" -> handleSearchByUsername(req);
            case "SetStuStatusA" -> handleSetA(req);
            case "SetStuStatusB" -> handleSetB(req);
            case "UpdateStuStatusA" -> handleUpdateA(req);
            case "UpdateStuStatusB" -> handleUpdateB(req);
            case "SearchAllStuStatus" -> handleSearchAll(req);
            default -> Response.error("不支持的操作类型: " + action);
        };
    }

    /**
     * 按ID查询学生学籍信息
     *
     * @param req 请求参数中应包含 id
     * @return 查询结果
     */
    private Response<?> handleSearchById(Request req) {
        Map<String, Object> params = req.getParams();
        try {
            Long id = Long.parseLong(params.get("id").toString());
            return studentService.SearchStuStatus(id);
        } catch (NumberFormatException e) {
            return Response.error("ID格式错误，请提供有效的数字");
        } catch (NullPointerException e) {
            return Response.error("ID参数不能为空");
        }
    }

    /**
     * 按用户名查询学生学籍信息
     *
     * @param req 请求参数中应包含 username
     * @return 查询结果
     */
    private Response<?> handleSearchByUsername(Request req) {
        Map<String, Object> params = req.getParams();
        try {
            String username = params.get("username").toString();
            return studentService.SearchStuStatus(username);
        } catch (NullPointerException e) {
            return Response.error("用户名参数不能为空");
        }
    }

    /**
     * 设置学生学籍信息（参数方式）
     *
     * @param req 请求参数中应包含 age, school_year, stu_id, class_id, college, emergency_num, family_num, semester
     * @return 设置结果
     */
    private Response<?> handleSetA(Request req) {
        Map<String, Object> params = req.getParams();
        try {
            Integer age = Integer.parseInt(params.get("age").toString());
            String schoolYear = params.get("school_year").toString();
            String stuId = params.get("stu_id").toString();
            String classId = params.get("class_id").toString();
            String college = params.get("college").toString();
            String emergencyNum = params.get("emergency_num").toString();
            Integer familyNum = Integer.parseInt(params.get("family_num").toString());
            String semester = params.get("semester").toString();

            return studentService.SetStuStatus(age, schoolYear, stuId, classId, college,
                    emergencyNum, familyNum, semester);
        } catch (NumberFormatException e) {
            return Response.error("年龄或家庭人数格式错误，请提供有效的数字");
        } catch (NullPointerException e) {
            return Response.error("设置学生状态的参数不能为空");
        }
    }

    /**
     * 设置学生学籍信息（对象方式）
     *
     * @param req 请求参数中应包含 age, school_year, stu_id, class_id, college, emergency_num, family_num, semester
     * @return 设置结果
     */
    private Response<?> handleSetB(Request req) {
        Map<String, Object> params = req.getParams();
        try {
            Integer age = Integer.parseInt(params.get("age").toString());
            String schoolYear = params.get("school_year").toString();
            String stuId = params.get("stu_id").toString();
            String classId = params.get("class_id").toString();
            String college = params.get("college").toString();
            String emergencyNum = params.get("emergency_num").toString();
            Integer familyNum = Integer.parseInt(params.get("family_num").toString());
            String semester = params.get("semester").toString();

            Student stu = new Student();
            stu.setAge(age);
            stu.setSchool_year(schoolYear);
            stu.setStudent_id(stuId);
            stu.setClass_id(classId);
            stu.setCollege(college);
            stu.setEmergency_number(emergencyNum);
            stu.setFamily_number(familyNum);
            stu.setMysemester(semester);

            return studentService.SetStuStatus(stu);
        } catch (NumberFormatException e) {
            return Response.error("年龄或家庭人数格式错误，请提供有效的数字");
        } catch (NullPointerException e) {
            return Response.error("设置学生状态的参数不能为空");
        }
    }

    /**
     * 更新学生学籍信息（参数方式）
     *
     * @param req 请求参数中应包含 stu_id, age, school_year, semester, class_id, college, emergency_num, family_num
     * @return 更新结果
     */
    private Response<?> handleUpdateA(Request req) {
        Map<String, Object> params = req.getParams();
        try {
            Integer age = Integer.parseInt(params.get("age").toString());
            String schoolYear = params.get("school_year").toString();
            String stuId = params.get("stu_id").toString();
            String classId = params.get("class_id").toString();
            String college = params.get("college").toString();
            String emergencyNum = params.get("emergency_num").toString();
            Integer familyNum = Integer.parseInt(params.get("family_num").toString());
            String semester = params.get("semester").toString();

            return studentService.UpdateStuStatus(stuId, age, schoolYear, semester, classId, college, emergencyNum, familyNum);
        } catch (NumberFormatException e) {
            return Response.error("ID、年龄或家庭人数格式错误，请提供有效的数字");
        } catch (NullPointerException e) {
            return Response.error("更新学生状态的参数不能为空");
        }
    }

    /**
     * 更新学生学籍信息（对象方式）
     *
     * @param req 请求参数中应包含 stu_id, age, school_year, semester, class_id, college, emergency_num, family_num
     * @return 更新结果
     */
    private Response<?> handleUpdateB(Request req) {
        Map<String, Object> params = req.getParams();
        try {
            String stuId = params.get("stu_id").toString();
            Integer age = Integer.parseInt(params.get("age").toString());
            String schoolYear = params.get("school_year").toString();
            String semester = params.get("semester").toString();
            String classId = params.get("class_id").toString();
            String college = params.get("college").toString();
            String emergencyNum = params.get("emergency_num").toString();
            Integer familyNum = Integer.parseInt(params.get("family_num").toString());

            Student stu = new Student();
            stu.setStudent_id(stuId);
            stu.setAge(age);
            stu.setSchool_year(schoolYear);
            stu.setClass_id(classId);
            stu.setCollege(college);
            stu.setEmergency_number(emergencyNum);
            stu.setFamily_number(familyNum);
            stu.setMysemester(semester);

            return studentService.UpdateStuStatus(stu);
        } catch (NumberFormatException e) {
            return Response.error("ID、年龄或家庭人数格式错误，请提供有效的数字");
        } catch (NullPointerException e) {
            return Response.error("更新学生状态的参数不能为空");
        }
    }

    /**
     * 查询所有学生学籍信息
     *
     * @param req 请求参数（无需参数）
     * @return 查询结果
     */
    private Response<?> handleSearchAll(Request req){
        return studentService.SearchAllStuStatus();
    }
}
